<template>
  <x-page>
    <x-filter @search="handleSearch" @reset="handleReset">
      <x-filter-item :label="'合同名称'">
        <el-input
          v-model="searchParams.contractName"
          :placeholder="'请输入合同名称'"
          clearable
          maxlength="100"
        ></el-input>
      </x-filter-item>
      <x-filter-item :label="'合同编号'">
        <el-input v-model="searchParams.number" :placeholder="'请输入合同编号'" clearable maxlength="100"></el-input>
      </x-filter-item>
      <x-filter-item :label="'状态'">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.state"
          :options="dictOptions['srm_contract.state']"
          style="width: 100%"
          clearable
        ></x-select>
      </x-filter-item>
      <x-filter-item :label="'合同类型'">
        <x-select
          :placeholder="$t('common.all')"
          v-model="searchParams.contractType"
          :options="dictOptions['srm_contract.contract_type']"
          style="width: 100%"
          clearable
        ></x-select>
      </x-filter-item>
      <x-filter-item :label="'签订日期'" :span="12">
        <el-date-picker
          v-model="searchParams.date"
          type="daterange"
          value-format="yyyy-MM-dd"
          :range-separator="$t('common.to')"
          :start-placeholder="'开始时间'"
          :end-placeholder="'结束时间'"
          clearable
        >
        </el-date-picker>
      </x-filter-item>
    </x-filter>
    <x-data>
      <template #tool>
        <el-row type="flex" class="tools" justify="space-between">
          <el-col :span="20">
            <!--            <el-button type="primary" :icon="buttonIcons('export')" @click="handleExportExcel"> {{ '导出' }}</el-button>-->
          </el-col>
          <el-col :span="4" class="tools-config">
            <x-column-config :columns="columns" @updateColumns="updateColumns" @on-refresh="loadData" />
          </el-col>
        </el-row>
      </template>
      <x-table
        ref="tableCom"
        :pagination="pagination"
        :data-source="tableData"
        :loading="loading"
        :row-key="'id'"
        @on-change="handleTableChange"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :label="$t('common.serialNumber')" :width="55" fixed type="index" />
        <el-table-column
          v-for="(item, index) in tableColumns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template #default="scope">
            <span v-if="item.prop === 'state'">{{
              selectDictLabel(dictOptions['srm_contract.state'], scope.row[item.prop])
            }}</span>
            <span v-else-if="item.prop === 'contractType'">{{
              selectDictLabel(dictOptions['srm_contract.contract_type'], scope.row[item.prop])
            }}</span>
            <span v-else-if="item.prop === 'beginDate' || item.prop === 'endDate'">{{
              replaceDateTime(scope.row[item.prop])
            }}</span>
            <span v-else-if="item.prop === 'contractAmount'">{{ parseFloat(scope.row[item.prop]).toFixed(2) }}</span>
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" :align="'center'" width="240">
          <template #default="scope">
            <more-table-actions
              :permis-list="permissionsActions"
              :action-list="getActions(actions, scope.row)"
              :row="scope.row"
              @onActionClick="handleActions"
            />
          </template>
        </el-table-column>
      </x-table>
    </x-data>
    <x-dialog
      :title="'回寄'"
      :close-on-click-modal="false"
      :show.sync="visible"
      :v-if="visible"
      append-to-body
      width="35%"
      :before-close="handleClose"
      @onCancel="handleClose"
      @onSubmit="handleSubmit"
    >
      <return-form ref="returnForm" :id="activeId"></return-form>
    </x-dialog>
  </x-page>
</template>

<script>
  import {
    buttonIcons,
    PermissionsMixin,
    QueryDictMixin,
    TableListMixin,
    selectDictLabel,
    replaceDateTime
  } from '@package/utils'
  import { columns, actions } from '@/modules/contractSupplier/config/manageContract.js'
  import { listUrl, apiMailContract } from '@/modules/contractSupplier/api/manageContract.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import ReturnForm from '@/modules/contractSupplier/components/ReturnForm.vue'

  export default {
    name: 'ManageContract',
    components: {
      ReturnForm
    },
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    data() {
      return {
        columns,
        actions,
        listUrl,
        searchParams: {
          contractName: '',
          number: '',
          state: '',
          contractType: '',
          date: ''
        },
        tableData: [],
        pagination: {
          pageSize: 10,
          pageNum: 1
        },
        srmDictKeys: ['srm_contract.state', 'srm_contract.contract_type'],
        visible: false,
        activeId: null
      }
    },
    computed: {
      getActions() {
        return (actions, row) => {
          const { state } = row
          return actions.map((action) => {
            const { key } = action
            switch (state) {
              case 1: // 待发送
                action.disabled = !['detail', 'send'].includes(key)
                break
              case 2: // 待确认
                action.disabled = !['detail', 'confirm'].includes(key)
                break
              case 3: // 待邮寄
                action.disabled = !['detail', 'mail'].includes(key)
                break
              case 4: // 待收件
                action.disabled = !['detail'].includes(key)
                break
              case 5: // 待回寄
                action.disabled = !['detail', 'returnSend'].includes(key)
                break
              case 6: // 待收回寄
                action.disabled = !['detail', 'complete'].includes(key)
                break
              case 7: // 已完成
                action.disabled = !['detail'].includes(key)
                break
              case 8: // 已退回
                action.disabled = !['detail'].includes(key)
                break
              case 9: // 已取消
                action.disabled = !['detail'].includes(key)
                break
              default:
                action.disabled = true
                break
            }
            return action
          })
        }
      }
    },
    methods: {
      replaceDateTime,
      buttonIcons,
      selectDictLabel,
      handleReset() {
        this.searchParams = {
          contractName: '',
          number: '',
          state: '',
          contractType: '',
          date: ''
        }
        this.resetSearch()
      },
      handleSearch(val) {
        const { contractName, number, state, contractType, date } = this.searchParams
        this.queryParam = {
          ...val,
          contractName,
          number,
          state,
          contractType,
          beginTime: date ? `${date[0]} 00:00:00` : '',
          endTime: date ? `${date[1]} 23:59:59` : ''
        }
        this.loadData()
      },
      async handleActions({ key, data }) {
        const { id } = data
        switch (key) {
          case 'complete':
          case 'confirm':
          case 'mail':
          case 'detail':
            await this.$router.push({
              name: 'ContractDetail',
              query: {
                id
              }
            })
            break
          default:
            break
        }
      },
      handleExportExcel() {
        this.handleExport('test')
      },
      handleClose() {
        this.activeId = null
        this.$refs.returnForm.resetForm()
        this.visible = false
      },
      async handleSubmit() {
        const returnForm = this.$refs.returnForm.form
        const confirm = await this.$confirm('是否确认邮寄?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (confirm) {
          const { code } = await apiMailContract({
            ...returnForm,
            type: 'reply'
          })
          if (code === EnumApiCode.Success) {
            this.$message.success('邮寄成功')
            this.loadData()
          }
        }
        this.$refs.returnForm.resetForm()
        this.visible = false
      }
    }
  }
</script>

<style scoped></style>
